import { Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';

@Component({
  selector: 'app-sys-user-roles',
  templateUrl: './roles.component.html'
})
export class SysUserRolesComponent implements OnInit {
  record: any = {};
  i: any;
  checked_values: number[] = [];

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, public http: _HttpClient) {}

  ngOnInit(): void {
    this.loadRoles();
  }

  save(): void {
    if (this.checked_values.length <= 0) {
      this.msgSrv.error('请至少勾选一个角色');
      return;
    }
    console.log(this.checked_values);
    this.http.post(`api/user/${this.record.ID}/roles`, { r_ids: this.checked_values }).subscribe(res => {
      if (res.err_code != 0) {
        this.msgSrv.error(res.msg);
        return;
      }
      this.msgSrv.success(res.msg);
      this.modal.close(false);
    });
  }

  close(): void {
    this.modal.destroy();
  }

  loadRoles(): void {
    this.http.get(`api/user/${this.record.ID}/roles`).subscribe(res => {
      this.i = res.data;
      for (let i = 0; i < this.i.length; i++) {
        if (this.i[i].Checked) {
          this.checked_values.push(this.i[i].ID);
        }
      }
    });
  }

  checkBoxChangeEvent(value: number[]): void {
    this.checked_values = value;
  }
}
